var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
layui.use(['laypage', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgId', title: '公司', width:120, align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'supplierName', title: '供应商', width: 200, align: 'center',templet: function (val) {
                if (isNull(val.supplierName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.supplierName + '</div>';
            }}
            ,{field: 'materialName', title: '材料', width: 200, align: 'center',templet: function (val) {
                if (isNull(val.materialName)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.materialName + '</div>';
            }}
            ,{field: 'weight', title: '固定重量(kg)', width:120, align: 'center'}
            ,{field: 'rate', title: '扣重比例(%)', width:120, align: 'center'}
            ,{field: 'type', title: '类型', width: 100, align: 'center',templet:function (val) {
                if (val.type == 0)
                    return '固定重量';
                else
                    return '比例';
            }}
            ,{field: 'status', title: '状态', width:108, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 220, align: 'center'}
            ,{field: 'creator', title: '创建人', width: 130, align: 'center'}
            ,{field: 'createTime', title: '创建时间', width: 140, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 200, align:'center', templet:function (val) {
                var str = '<a lay-event="detail" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-primary">详情</a>';
                if (val.status == 0){
                    if (isDelete == 1)
                        str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">删除</a>';
                    if (isUpdate == 1)
                        str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                }
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/mainmaterialdiscount/page'
        ,method: 'post'
        ,page: true
        ,contentType: 'application/json'
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res);
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要删除？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option =  '{"id": '+id+', "status":'+updateStatus+'}';
                save(option, "/mainmaterialdiscount/updatestatus");
            }, function(index){
            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            $("#updateTitle").text("修改材料扣重设置");
            $('#update-mainDiscount-body').show();
            $('.update-search-origin').val(data.orgId);
            loadMaterialList({orgId: data.orgId, materialId: data.materialId});
            getSupplierList({orgId: data.orgId,supplierId: data.supplierId });
            $(".update-type").val(data.type);
            if (data.type == 1) {
                $(".update-rate-show").show();
                $(".update-weight-show").hide();
                $(".update-rate").val(data.rate);
            } else {
                $(".update-weight-show").show();
                $(".update-rate-show").hide();
                $(".update-weight").val(data.weight);
            }
            $(".update-remark").val(data.remark);
            $("#updateBtn").show();
            form.render();
        } else  if(layEvent === 'detail'){
            $("#updateTitle").text("查询材料扣重设置");
            $('#update-mainDiscount-body').show();
            $('.update-search-origin').val(data.orgId);
            loadMaterialList({orgId: data.orgId,supplierId: data.supplierId, materialId: data.materialId});
            getSupplierList({orgId: data.orgId,supplierId: data.supplierId });
            $(".update-type").val(data.type);
            if (data.type == 1) {
                $(".update-rate-show").show();
                $(".update-weight-show").hide();
                $(".update-rate").val(data.rate);
            } else {
                $(".update-weight-show").show();
                $(".update-rate-show").hide();
                $(".update-weight").val(data.weight);
            }
            $(".update-remark").val(data.remark);
            $("#updateBtn").hide();
            form.render();
        }
    });

    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-type)', function(data) {
        $(".btn-query").trigger("click");
    });
    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var status = $('.search-status').val();
        var orgId = $('.search-origin').val();
        var type = $('.search-type').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(type))
            option['type'] = type;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        table.reload('body-list', {
            where: option
        });
    });

    $("#update-mainDiscount-body .close").on("click", function() {
        $("#update-mainDiscount-body").hide();
        $("#update-mainDiscount-body-body input").val("");
        $("#update-mainDiscount-body select").val("");
        $("#update-mainDiscount-body textarea").val("");
        $(".qrcode-show").hide();
        form.render();
        tid = -1;
    });

    //新增页面选择类型
    form.on('select(update-type)', function(data) {
        if (data.value == 1) {
            $(".update-rate-show").show();
            $(".update-weight-show").hide();
            $(".update-rate").val('');
        } else {
            $(".update-weight-show").show();
            $(".update-rate-show").hide();
            $(".update-weight").val('');
        }
    });

    form.on('submit(updateBtns)', function() {
        var options = null;
        var orgId = $(".update-search-origin").val();
        var materialId = $(".update-material").val();
        var supplierId = $(".update-supplier").val();
        var type = $(".update-type").val();
        var weight = $(".update-weight").val();
        var rate = $(".update-rate").val();
        var remark = $(".update-remark").val();
        if (materialId == null) {
            layer.msg('请选择材料~！');
            return;
        }
        if(type == '0'){
            if (isNull(weight)) {
                layer.msg("请输入固定重量(kg)！");
                return ;
            }
            options = '{"orgId":'+orgId+', "materialId":'+materialId+', "supplierId":'+supplierId+', "type":'+type+', "weight":'+weight+', "remark":"'+remark+'", "id":'+tid+'}';
        }else{
            if (isNull(rate)) {
                layer.msg("请输入扣重比例(%)！");
                return ;
            }
            options = '{"orgId":'+orgId+', "materialId":'+materialId+', "supplierId":'+supplierId+', "type":'+type+', "rate":'+rate+', "remark":"'+remark+'", "id":'+tid+'}';
        }
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        save(options, "/mainmaterialdiscount/update");
    });

    //新增页面选择类型
    form.on('select(add-type)', function(data) {
        if (data.value == 1) {
            $(".add-rate-show").show();
            $(".add-weight-show").hide();
            $(".add-rate").val('');
        } else {
            $(".add-weight-show").show();
            $(".add-rate-show").hide();
            $(".add-weight").val('');
        }
    });

    //新增页面选择类型
    form.on('select(add-search-origin)', function(data) {
        if (data.value != null) {
            loadMaterialList({orgId: $(".add-search-origin").val()});
            getSupplierList({orgId: $(".add-search-origin").val()});
        }
    });
    form.on('select(add-supplier)', function(data) {
        if (data.value != null)
            loadMaterialList({orgId: $(".add-search-origin").val(),supplierId:data.value});
    });
    form.on('select(update-search-origin)', function(data) {
        if (data.value != null) {
            loadMaterialList({orgId: $(".update-search-origin").val()});
            getSupplierList({orgId: $(".update-search-origin").val()});
        }
    });
    form.on('select(update-supplier)', function(data) {
        if (data.value != null)
            loadMaterialList({orgId: $(".update-search-origin").val(),supplierId:data.value});
    });
    //打开新增页面
    $('.btn-add').on('click', function () {//新增流程
        if (isInsert == 0) {
            layer.msg('你没有操作权限~！');
            return ;
        }
        $('.addModal').show();
        $(".add-weight-show").show();
        $(".add-rate-show").hide();
        loadMaterialList({orgId: $(".add-search-origin").val()});
        getSupplierList({orgId: $(".add-search-origin").val()});
    });

    //关闭新增页面
    $(".addModal .close").on("click", function () {//关闭新增流程窗口
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });

    //新增
    form.on('submit(addBtns)', function () {
        var option = null;
        var orgId = $(".add-search-origin").val();
        var materialId = $(".add-material").val();
        var supplierId = $(".add-supplier").val();
        var type = $(".add-type").val();
        var weight = $(".add-weight").val();
        var rate = $(".add-rate").val();
        var remark = $(".add-remark").val();
        if(type == '0'){
            if (isNull(weight)) {
                layer.msg("请输入固定重量(kg)！");
                return ;
            }
            option = '{"orgId":'+orgId+', "materialId":'+materialId+', "supplierId":'+supplierId+', "type":'+type+', "weight":'+weight+',"remark":"'+remark+'"}';
        }else{
            if (isNull(rate)) {
                layer.msg("请输入扣重比例(%)！");
                return ;
            }
            option = '{"orgId":'+orgId+', "materialId":'+materialId+', "supplierId":'+supplierId+', "type":'+type+', "rate":'+rate+',"remark":"'+remark+'"}';
        }
        save(option,"/mainmaterialdiscount/save");
    });


    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        console.log(option);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("保存成功!");
                    table.reload('body-list', { where: {offset:0,curr:1,
                            limit: limit,
                            orgId:$('.search-origin').val() }});
                    $("#update-mainDiscount-body").hide();
                    $("#update-mainDiscount-body input").val("");
                    $("#update-mainDiscount-body select").val("");
                    $("#update-mainDiscount-body textarea").val("");
                    $("#add-mainDiscount-body").hide();
                    $("#add-mainDiscount-body input").val("");
                    $("#add-mainDiscount-body select").val("");
                    $("#add-mainDiscount-body textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }



    //获取单位关联的材料类型信息
    function loadMaterialList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/mainmaterialdiscount/getMaterialList',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择材料</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.add-material').html(html);
                    $('.update-material').html(html);
                } else {
                    $('.add-material').html('<option value="">暂无数据</option>');
                    $('.update-material').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.materialId)) {
                    $('.update-material').val(obj.materialId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    //加载供应商信息
    function getSupplierList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/mainmaterialdiscount/getSupplierList',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            success: function (res) {
                console.log(res)
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择供应商</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.add-supplier').html(html);
                    $('.update-supplier').html(html);
                } else {
                    $('.add-supplier').html('<option value="">暂无数据</option>');
                    $('.update-supplier').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj.supplierId)) {
                    $('.update-supplier').val(obj.supplierId);
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $(".btn-query").trigger("click");
        }
    });
});